package com.zj.leetcode.easy.tree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @program: algorithm
 * @description: 二叉树的层平均值
 * 637 average-of-levels-in-binary-tree
 * @author: Zhang Bo
 * @create: 2022-06-15 11:02:11
 **/
public class AverageOfLevelsInBinaryTree {
    public static void main(String[] args) {
        Solution solution = new AverageOfLevelsInBinaryTree().new Solution();
    }
    //leetcode submit region begin(Prohibit modification and deletion)

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    class Solution {
        public List<Double> averageOfLevels(TreeNode root) {
            List<Double> res = new ArrayList<>();

            if (root == null) {
                return res;
            }

            Queue<TreeNode> queue = new LinkedList<>();
            queue.add(root);
            while (queue.size() != 0) {
                int size = queue.size();
                long total = 0;
                for (int i = 0; i < size; i++) {
                    TreeNode poll = queue.poll();
                    if (poll != null) {
                        total += poll.val;
                    }
                    queue.add(poll);
                }
                res.add((double) total / size);

                for (int i = 0; i < size; i++) {
                    TreeNode poll = queue.poll();
                    if (poll != null) {
                        if(poll.left != null){
                            queue.add(poll.left);
                        }
                        if(poll.right != null){
                            queue.add(poll.right);
                        }
                    }

                }
            }

            return res;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}
